package com.itcast.rpc.client.zk;

import com.itcast.common.annotation.RpcClient;
import com.itcast.rpc.client.cache.ServiceRouteCache;
import com.itcast.rpc.client.channel.ProviderService;
import com.itcast.rpc.client.config.RpcClientConfiguration;
import org.apache.commons.collections.CollectionUtils;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

/**
 * 注册服务拉取管理器
 */
@Component
public class ServicePullManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServicePullManager.class);

    /**
     * ZK客户端工具
     */
    @Autowired
    private ZKit zKit;

    /**
     * 服务路由缓存
     */
    @Autowired
    private ServiceRouteCache serviceRouteCache;

    /**
     * RPC客户端配置
     */
    @Autowired
    private RpcClientConfiguration configuration;

    /**
     * 服务订阅处理接口
     */
    public void pullServiceFromZK() {
        // 1. 获取指定包下所有的@RpcClient注解的接口
        Reflections reflections = new Reflections(configuration.getRpcClientApiPackage());
        Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(RpcClient.class);

        if (CollectionUtils.isNotEmpty(typesAnnotatedWith)){
            for (Class<?> cls : typesAnnotatedWith) {
                String serviceName = cls.getName();
                // 2. 根据接口的名字去Zookeeper 获取接口名字对应的节点数据
                List<ProviderService> providerServices = zKit.getServiceInfos(serviceName);
                // 3. 缓存服务列表数据
                serviceRouteCache.addCache(serviceName,providerServices);
                zKit.subscribeZKEvent(serviceName);
            }
        }





    }
}
